﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FillCartridgeBBB.Models
{
    public class DepartmentRepository
    {

        private FillCartridgeDbEntities _db;

        public DepartmentRepository (FillCartridgeDbEntities db)
        {
            _db = db;
        }

        public IEnumerable<Department> SelectAll ()
        {
            return _db.DepartmentSet.Include("Printers");
        }

        public Department SelectById (int id)
        {
            return _db.DepartmentSet.Include("Printers").First(d => d.DepartmentId == id);
        }

        public IEnumerable<Department> SelectByPrinter(Printer printer)
        {
            return _db.DepartmentSet.Where(d => d.Printers.Any(p => p.PrinterId == printer.PrinterId));
        }

        public void Insert(Department department, string printers)
        {
            var prts = printers.Split(',');
            foreach (var printerId in prts)
            {
                if (printerId != "false")
                {
                    int id = int.Parse(printerId);
                    Printer printer = _db.PrinterSet.Where(prt => prt.PrinterId == id).First();
                    department.Printers.Add(printer);
                }
            }
            _db.AddToDepartmentSet(department);
            _db.SaveChanges();
        }

        public void Delete(int id)
        {
            _db.DeleteObject(SelectById(id));
            _db.SaveChanges();
        }

        public void Update(Department department, string printers)
        {
            Department dbDep = SelectById(department.DepartmentId);
            dbDep.Name = department.Name;
            dbDep.Adress = department.Adress;
            var prts = printers.Split(',');
            dbDep.Printers.Clear();
            foreach (var printerId in prts)
            {
                if (printerId != "false")
                {
                    int id = int.Parse(printerId);
                    Printer printer = _db.PrinterSet.Where(prt => prt.PrinterId == id).First();
                    dbDep.Printers.Add(printer);
                }
            }
            _db.SaveChanges();
        }

    }
}
